package com.risk.management.controller;

import com.risk.management.dto.Result;
import com.risk.management.entity.Project;
import com.risk.management.entity.ProjectMember;
import com.risk.management.entity.User;
import com.risk.management.service.ProjectMemberService;
import com.risk.management.service.ProjectService;
import com.risk.management.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 项目成员控制器
 */
@Controller
@RequestMapping("/project-member")
public class ProjectMemberController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProjectMemberController.class);

    @Autowired
    private ProjectMemberService projectMemberService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private UserService userService;

    /**
     * 项目成员管理主页
     */
    @GetMapping("/manage")
    public String manage(Model model) {
        logger.info("访问项目成员管理主页");
        // 获取所有项目
        List<Project> projects = projectService.getAllProjects();
        model.addAttribute("projects", projects);
        return "project-member/manage";
    }

    /**
     * 项目成员列表页面
     */
    @GetMapping("/list/{projectId}")
    public String list(@PathVariable Long projectId, Model model) {
        logger.info("访问项目成员列表，项目ID: {}", projectId);
        // 获取项目信息
        Project project = projectService.getProjectById(projectId);
        if (project == null) {
            logger.warn("项目不存在，ID: {}", projectId);
            return "redirect:/project/list";
        }
        
        // 获取项目成员
        List<User> members = projectMemberService.getUsersByProjectId(projectId);
        List<ProjectMember> memberRelations = projectMemberService.getProjectMembersByProjectId(projectId);
        
        model.addAttribute("project", project);
        model.addAttribute("members", members);
        model.addAttribute("memberRelations", memberRelations);
        
        // 获取所有用户（用于添加成员）
        List<User> allUsers = userService.getAllUsers();
        model.addAttribute("allUsers", allUsers);
        
        // 获取所有项目（用于项目选择）
        List<Project> allProjects = projectService.getAllProjects();
        model.addAttribute("allProjects", allProjects);
        
        return "project-member/list";
    }

    /**
     * 添加项目成员页面
     */
    @GetMapping("/add/{projectId}")
    public String add(@PathVariable Long projectId, Model model) {
        logger.info("访问添加项目成员页面，项目ID: {}", projectId);
        Project project = projectService.getProjectById(projectId);
        if (project == null) {
            logger.warn("项目不存在，ID: {}", projectId);
            return "redirect:/project/list";
        }
        
        // 获取所有用户（用于选择成员）
        List<User> users = userService.getAllUsers();
        
        // 过滤掉已经是项目成员的用户
        List<User> existingMembers = projectMemberService.getUsersByProjectId(projectId);
        users.removeIf(user -> existingMembers.stream().anyMatch(member -> member.getId().equals(user.getId())));
        
        model.addAttribute("project", project);
        model.addAttribute("users", users);
        
        // 获取所有项目（用于项目选择）
        List<Project> allProjects = projectService.getAllProjects();
        model.addAttribute("allProjects", allProjects);
        
        return "project-member/add";
    }
    
    /**
     * 添加项目成员通用页面 - 可选择项目
     */
    @GetMapping("/add")
    public String addToAnyProject(Model model) {
        logger.info("访问通用添加项目成员页面");
        
        // 获取所有用户
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        
        // 获取所有项目
        List<Project> projects = projectService.getAllProjects();
        model.addAttribute("projects", projects);
        
        return "project-member/add-any";
    }

    /**
     * 添加项目成员 - 表单提交接口
     */
    @PostMapping("/add")
    @ResponseBody
    public Result<Void> add(
            @RequestParam Long projectId,
            @RequestParam Long userId,
            @RequestParam Integer role) {
        
        // 打印接收到的参数
        logger.info("添加单个成员请求 - 表单参数: projectId={}, userId={}, role={}", 
                   projectId, userId, role);
        
        // 创建项目成员对象
        ProjectMember projectMember = new ProjectMember();
        projectMember.setProjectId(projectId);
        projectMember.setUserId(userId);
        projectMember.setRole(role);
        
        logger.info("添加项目成员: {}", projectMember);
        try {
            boolean success = projectMemberService.addProjectMember(projectMember);
            if (success) {
                return Result.success();
            } else {
                return Result.error("添加项目成员失败，该用户可能已经是项目成员");
            }
        } catch (Exception e) {
            logger.error("添加项目成员异常: {}", e.getMessage(), e);
            return Result.error("添加项目成员时发生异常: " + e.getMessage());
        }
    }

    /**
     * 批量添加项目成员 - 表单提交接口
     */
    @PostMapping("/batch-add")
    @ResponseBody
    public Result<Void> batchAdd(
            @RequestParam Long projectId, 
            @RequestParam(value = "userIds[]", required = false) List<Long> userIdsList,
            @RequestParam(value = "userIds", required = false) List<Long> userIds,
            @RequestParam Integer role) {
        
        // 打印接收到的参数用于调试
        logger.info("接收到批量添加请求，参数: projectId={}, userIds[]={}, userIds={}, role={}", 
                   projectId, userIdsList, userIds, role);
        
        // 合并两种可能的参数名
        List<Long> finalUserIds = userIdsList != null ? userIdsList : userIds;
        
        logger.info("批量添加项目成员, 项目ID: {}, 用户IDs: {}, 角色: {}", projectId, finalUserIds, role);
        
        if (finalUserIds == null || finalUserIds.isEmpty()) {
            return Result.error("用户ID列表不能为空");
        }
        
        try {
            boolean success = projectMemberService.addProjectMembers(projectId, finalUserIds, role);
            if (success) {
                return Result.success();
            } else {
                return Result.error("批量添加项目成员失败");
            }
        } catch (Exception e) {
            logger.error("批量添加项目成员异常: {}", e.getMessage(), e);
            return Result.error("批量添加项目成员时发生异常: " + e.getMessage());
        }
    }

    /**
     * 更新项目成员角色 - 表单提交接口
     */
    @PostMapping("/update-role")
    @ResponseBody
    public Result<Void> updateRole(@RequestParam Long projectId, @RequestParam Long userId, @RequestParam Integer role) {
        logger.info("更新项目成员角色, 项目ID: {}, 用户ID: {}, 新角色: {}", projectId, userId, role);
        try {
            boolean success = projectMemberService.updateProjectMemberRole(projectId, userId, role);
            if (success) {
                return Result.success();
            } else {
                return Result.error("更新项目成员角色失败");
            }
        } catch (Exception e) {
            logger.error("更新项目成员角色异常: {}", e.getMessage(), e);
            return Result.error("更新项目成员角色时发生异常: " + e.getMessage());
        }
    }

    /**
     * 删除项目成员 - 表单提交接口
     */
    @PostMapping("/delete")
    @ResponseBody
    public Result<Void> delete(@RequestParam Long projectId, @RequestParam Long userId) {
        logger.info("删除项目成员, 项目ID: {}, 用户ID: {}", projectId, userId);
        try {
            boolean success = projectMemberService.deleteProjectMember(projectId, userId);
            if (success) {
                return Result.success();
            } else {
                return Result.error("删除项目成员失败");
            }
        } catch (Exception e) {
            logger.error("删除项目成员异常: {}", e.getMessage(), e);
            return Result.error("删除项目成员时发生异常: " + e.getMessage());
        }
    }

    /**
     * 检查用户是否是项目成员 - JSON接口
     */
    @GetMapping("/check")
    @ResponseBody
    public Result<Boolean> checkIsMember(@RequestParam Long projectId, @RequestParam(required = false) Long userId) {
        // 如果没有传递userId，则返回false
        if (userId == null) {
            return Result.success(false);
        }
        boolean isMember = projectMemberService.isMember(projectId, userId);
        return Result.success(isMember);
    }
    
    /**
     * 获取可添加用户列表 - AJAX接口
     */
    @GetMapping("/available-users")
    @ResponseBody
    public Result<List<User>> getAvailableUsers(@RequestParam Long projectId) {
        try {
            // 获取所有用户
            List<User> allUsers = userService.getAllUsers();
            
            // 获取项目已有成员
            List<User> existingMembers = projectMemberService.getUsersByProjectId(projectId);
            
            // 过滤掉已经是项目成员的用户
            allUsers.removeIf(user -> existingMembers.stream().anyMatch(member -> member.getId().equals(user.getId())));
            
            return Result.success(allUsers);
        } catch (Exception e) {
            logger.error("获取可添加用户列表异常: {}", e.getMessage(), e);
            return Result.error("获取可添加用户列表失败");
        }
    }
} 